<template>
  <el-dialog title="新增部门" :visible="showDialog" @close="close">
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          size="mini"
          style="width: 80%"
          placeholder="2-10个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="2-10个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="managerId">
        <el-select
          v-model="formData.managerId"
          placeholder="请选择负责人"
          style="width: 80%"
          size="mini"
        >
          <!-- 下拉选项 循环 负责人数据 label表示显示的字段 value 存储字段 -->
          <el-option
            v-for="item in ManagerList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          type="textarea"
          style="width: 80%"
          placeholder="1-100个字符"
          :rows="4"
          size="mini"
        />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="submitForm"
              >确定</el-button
            >
            <el-button size="mini" @click="close">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
import {
  getDepartment,
  getManagerList,
  addDepartment,
  getDepartmentDetail,
  updateDepartment
} from '@/api/department'
export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      ManagerList: [],
      formData: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      },
      rules: {
        name: [
          {
            required: true,
            message: '部门名称不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '部门名称2-10个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async (rule, value, callback) => {
              // value就是输入的编码
              let result = await getDepartment()
              // 过滤result数组的item.id===formData.id
              if (this.formData.id) {
                result = result.filter(item => item.id !== this.formData.id)
              }
              // result数组中是否存在 value值
              if (result.some(item => item.name === value)) {
                callback(new Error('部门中已经有该名称了'))
              } else {
                callback()
              }
            }
          }
        ],
        code: [
          {
            required: true,
            message: '部门编码不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '部门编码长度2-10个字符',
            trigger: 'blur'
          },
          {
            trigger: 'blur',
            validator: async (rule, value, callback) => {
              let result = await getDepartment()
              if (this.formData.id) {
                result = result.filter(item => item.id !== this.formData.id)
              }
              if (result.some(item => item.code === value)) {
                callback(new Error('部门中已经有该编号了'))
              } else {
                callback()
              }
            }
          }
        ],
        managerId: [
          {
            required: true,
            message: '负责人不能为空',
            trigger: 'blur'
          }
        ],
        introduce: [
          {
            required: true,
            message: '部门介绍不能为空',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 10,
            message: '部门介绍长度1-100个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getManagerList()
  },
  methods: {
    // 关闭弹层
    close() {
      this.$refs.addDept.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 确认（添加部门、编辑部门）
    submitForm() {
      this.$refs.addDept.validate(async valid => {
        if (valid) {
          let msg = '添加'
          if (this.formData.id) {
            msg = '更新'
            await updateDepartment(this.formData)
          } else {
            await addDepartment({
              ...this.formData,
              pid: this.currentNodeId
            })
          }
          this.$emit('addDept')
          this.$message.success(`${msg}部门成功`)
          this.close()
        }
      })
    },
    // 获取负责人列表
    async getManagerList() {
      this.ManagerList = await getManagerList()
    },
    // 编辑部门的渲染
    async operateDept() {
      // 获取部门详情
      this.formData = await getDepartmentDetail(this.currentNodeId)
    }
  }
}
</script>
